import { post } from '@/axios/http'
import comFunc from '@/common/comFunc'
import { Sysinfo } from '@/common/config'

export const queryUsersBy = async (p: {
  categoryId?: string
  name?: string
  pageSize?: number
  to?: number
}): Promise<{
  isSuccess: boolean
  msg: string
  data?: any[]
  pageSize?: number
  pageNum?: number
  totalRow?: number
  totalPages?: number
}> => {
  if (!p.pageSize) p.pageSize = Sysinfo.PageSize
  if (!p.to) p.to = 1
  const re = await post('/project/user/queryAllUser', {
    name: comFunc.nvl(p.name) === '' ? null : p.name,
    pageNum: p.to,
    pageSize: p.pageSize
  }).catch((err) => {
    return err.response || err
  })
  const data =
    re.data && re.data.data
      ? re.data.data
      : {
          list: [],
          pageSize: Sysinfo.PageSize,
          pageNum: 1,
          totalRow: 0,
          totalPages: 0
        }
  if (re.data) {
    if (re.data.success) {
      const list = [] as any[]
      data.list?.forEach((item) => {
        const info = {
          uid: item.objectId,
          loginid: item.loginName,
          loginname: item.name,
          userno: '',
          usertype: 'System',
          loginpass: '',
          mobile: item.phone,
          qq: '',
          avatar: item.imgPath,
          roles: item.role ? item.role.split(',') : []
        }
        list.push(info)
      })
      return {
        isSuccess: re.data.success,
        msg: re.data.message,
        data: list,
        pageSize: data.pageSize > 0 ? data.pageSize : Sysinfo.PageSize,
        pageNum: data.pageNum,
        totalRow: data.total,
        totalPages: data.pages
      }
    } else {
      return {
        isSuccess: re.data.success,
        msg: re.data.message
      }
    }
  } else {
    return {
      isSuccess: false,
      msg: `查询失败:无返回结果`
    }
  }
}
export const updateUser = async (
  data: UserModel
): Promise<{
  isSuccess: boolean
  msg: string
}> => {
  let postdata = {
    imgPath: data.avatar,
    loginName: data.loginid,
    name: data.loginname,
    objectId: data.uid,
    openId: '',
    phone: data.mobile,
    role: data.roles ? data.roles[0] : '',
    roleId: data.roleId ? data.roleId[0] : ''
  }
  const re = await post('/project/user/updateUser', postdata).catch((err) => err.response || err)
  if (!re)
    return {
      isSuccess: false,
      msg: '操作失败：服务端操作失败'
    }
  if (!re.data)
    return {
      isSuccess: false,
      msg: '操作失败：服务端未返回结果'
    }
  return {
    isSuccess: re.data.success,
    msg: re.data.message || '操作失败: 未知错误'
  }
}
